﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace LocalFileGoSvr.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private string rootPath = "Z:\\tmp\\books\\";

        // GET api/<FilesController>/5
        //[HttpGet]
        [HttpGet("{path?}")]
        public FileResponse Get(string path = "")
        {
            var fr = new FileResponse();
            fr.Files = new List<FileBaseInfo>();
            var truePath = rootPath;
            if (!string.IsNullOrEmpty(path)) { 
                var p = Base64UrlTextEncoder.Decode(path);
                var pStr = Encoding.UTF8.GetString(p);
                var pStrList = pStr.Split('\\').Where(x=>!string.IsNullOrWhiteSpace(x)).ToArray();
                fr.RootPath = pStrList;
                truePath = rootPath + pStr;
                fr.Paths = new string[pStrList.Length];
                var r = "";
                for (int i = 0; i < pStrList.Length; i++)
                { 
                    var p1 = (r == "" ? r : r + "\\")+ pStrList[i];
                    r = p1;
                    fr.Paths[i] = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(p1));
                }
            }
            var dirs = Directory.GetDirectories(truePath);
            foreach (var dir in dirs) {
                var dirInfo = new DirectoryInfo(dir);
                var p = dirInfo.FullName.Replace(rootPath, "");
                var encP = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(p));
                fr.Files.Add(new FileBaseInfo(dirInfo.Name, encP, true));
            }
            var files = Directory.GetFiles(truePath);
            foreach (var file in files) {
                var fileInfo = new FileInfo(file);
                var p = fileInfo.FullName.Replace(rootPath, "").Replace(fileInfo.Name, "");
                fr.Files.Add(new FileBaseInfo(fileInfo.Name, "", false));
            }
            return fr;
        }

        // POST api/<FilesController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<FilesController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<FilesController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
